package com.bootdo.common.task;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.huobi.api.ApiClient;
import com.bootdo.common.huobi.request.CreateOrderRequest;
import com.bootdo.common.huobi.response.Accounts;
import com.bootdo.common.huobi.response.AccountsResponse;
import com.bootdo.common.huobi.response.BalanceResponse;
import com.bootdo.common.utils.CalculationUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.timing.domain.CombDO;
import com.bootdo.timing.domain.OrderDO;
import com.bootdo.timing.service.CombService;
import com.bootdo.timing.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class HuoJob implements Job {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //每隔10分钟获取火币网数据
    @Autowired
    private CombService combService;
    @Autowired
    private OrderService orderService;

    private static String API_KEY = "de2162ba-931a9dda-88f3caa2-uymylwhfeg";

    private static String API_SECRET = "edcc7848-06c8ea9a-3995ea0e-07db4";


    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            List<CombDO> list = combService.list(new HashMap<>());
            for (int i = 0; list.size() > i; i++) {
                CombDO combDO = list.get(i);
                ApiClient client = new ApiClient(API_KEY, API_SECRET);
                if (!StringUtils.isEmpty(combDO.getJson())) {
                    BigDecimal buy_amount = combDO.getAmount(); // 购买总金额
                    AccountsResponse accounts = client.accounts(); // 账号列表
                    if (accounts==null || !"ok".equals(accounts.getStatus())) {
                        return;
                    }
                    System.out.println(accounts);
                    JSONObject jsonObject = JSON.parseObject(combDO.getJson());
                    logger.info("--------------------balance begin -------------------------");
                    logger.info("{}", accounts);
                    logger.info("--------------------balance end -------------------------");
                    //------------------------------------------------------ balance -------------------------------------------------------
                    List<Accounts> accountlist = (List<Accounts>) accounts.getData();
                    BalanceResponse balance = client.balance(String.valueOf(accountlist.get(0).getId()));
                    if (balance == null || !"ok".equals(balance.getStatus())) {
                        return;
                    }
                    logger.info("--------------------balance begin -------------------------");
                    logger.info("{}", balance);
                    logger.info("--------------------balance end -------------------------");
                    Long orderId = 123L;
                    // find account id:
                    Accounts account = accountlist.get(0);
                    long accountId = account.getId();
                    int total_sacle = 0;
                    for (String k : jsonObject.keySet()) {
                        total_sacle += Integer.parseInt(jsonObject.get(k) + "");
                    }

                    for (String key : jsonObject.keySet()) {
                        if (!accountlist.isEmpty()) {
                            // create order:
                            CreateOrderRequest createOrderReq = new CreateOrderRequest();
                            createOrderReq.accountId = String.valueOf(accountId);
                            String sacle = jsonObject.get(key) + "";
                            String divide_salce = CalculationUtil.divide(String.valueOf(buy_amount), String.valueOf(total_sacle), 4);
                            String buy_total_amount = CalculationUtil.multiply(divide_salce, sacle, 4);
                            createOrderReq.amount = buy_total_amount; //购买的金额
                            createOrderReq.symbol = key + "usdt"; // 币种
                            createOrderReq.type = CreateOrderRequest.OrderType.BUY_MARKET;
                            createOrderReq.source = "api";
                            //------------------------------------------------------ 创建订单  -------------------------------------------------------
                            orderId = 63082247609L; // orderId= client.createOrder(createOrderReq);
                            logger.info("--------------------balance begin -------------------------");
                            logger.info("{}", orderId);
                            logger.info("--------------------balance end -------------------------");
                            // 获取订单
                            OrderDO orderDO = new OrderDO();
                            orderDO.setUserId(combDO.getUserId());
                            orderDO.setCombId(combDO.getId());
                            orderDO.setBuyAmount(new BigDecimal(buy_total_amount));
                            orderDO.setCurrencyType(key + "usdt");
                            orderDO.setCreateTime(new Date());
                            orderDO.setTradeOrder(String.valueOf(orderId)); // 交易订单号
                            orderDO.setUpdateTime(new Date());
                            orderDO.setState(1); // 创建订单状态
                            orderDO.setTradeOrder(orderId.toString()); // 请求订单
                            orderDO.setScale(Integer.parseInt(jsonObject.get(key) + ""));
                            orderService.save(orderDO);
                        }

                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}